import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from '../../../../shared/blade/blade-container-base';
import { TurboperCategory } from '../../../../entity/turboper-category.model';
import { FormBuilder, Validators, FormControl } from '@angular/forms';
import { Command } from '../../../../shared/toolbar.service';
import { Observable } from 'rxjs/Observable';
import { TurboperCategoryService } from '../../../../service/turboper-category.service';
import { TurbStatus } from '../../../../entity/turbstatus.model';
import { Setofvalue } from '../../../../entity/setofvalue.model';


@Component({
  selector: 'app-turboper-category-edit',
  templateUrl: './turboper-category-edit.component.html',
  styleUrls: ['./turboper-category-edit.component.css']
})
export class TurboperCategoryEditComponent extends BladeContainerBase<TurboperCategory>{

  //风机状态集合
  turbStatus: TurbStatus[] = [];
  setofvalues: Setofvalue[] = [];
  //不能设置的状态数组
  notStatusAry: string[] = [];
  //分类数组
  generalCategoryAry: string[] = [];

  //选中的状态数组
  checkStatusAry: string[] = [];
  //选中的分类数组
  checkgeneralCategoryAry: string[] = [];

  //图标
  operCategoryIcon: string;


  constructor(
    private fb: FormBuilder,
    private turboperCategoryService: TurboperCategoryService,
  ) {
    super(fb);
  }

  ngOnInit() {
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new TurboperCategory(0, '', '', '', false, false, false, 0, '', '', '');

    }
    super.ngOnInit();
    // this.initData();
  }

  initData(): any | Observable<any> | Promise<any> {
    this.turbStatus = [...this.parentEntity.turbStatus];
    this.setofvalues = [...this.parentEntity.setofvalues];
    this.operCategoryIcon = this.currentEntity.operCategoryIcon;

    this.notStatusAry = this.currentEntity.notAllowWhenStatus.split('|');
    if (this.notStatusAry[0] == '') {
      this.notStatusAry.shift()
    }
    this.checkStatusAry = [...this.notStatusAry]



    this.generalCategoryAry = this.currentEntity.generalCategory.split('|');
    if (this.generalCategoryAry[0] == '') {
      this.generalCategoryAry.shift();
    }
    this.checkgeneralCategoryAry = [...this.generalCategoryAry]


    this.setofvalues.forEach(s => {
      s.isChecked = false;
      if (this.generalCategoryAry != undefined) {
        this.generalCategoryAry.forEach(g => {
          if (s.valueCode == g) {
            s.isChecked = true;
          }
        })
      }
    })

    this.turbStatus.forEach(t => {
      t.isChecked = false;
      if (this.checkStatusAry != undefined) {
        this.checkStatusAry.forEach(a => {
          if (Number(a) == t.statusValue) {
            t.isChecked = true;
          }
        })
      }
    })

  }





  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    return this.hasChange() || this.hasturbStatuChange() && !this.hasError();
  }

  exeReset(blade: any): void {

    this.refresh();

    this.formGroup.reset(this.currentEntity);

  }

  canReset(blade: any): boolean {
    return this.hasChange() || this.hasturbStatuChange();
  }

  //刷新
  refresh() {
    this.checkStatusAry = [];
    this.notStatusAry.forEach(f => {
      this.checkStatusAry.push(f)
    })
    // this.turbStatus.forEach(t => {
    //   t.isChecked = false;
    //   if (this.checkStatusAry != undefined) {
    //      this.checkStatusAry.forEach(a => {
    //       if (Number(a) == t.statusValue) {
    //         t.isChecked = true;
    //       }
    //     }) 
    //   }
    // })



    this.checkgeneralCategoryAry = [];
    this.generalCategoryAry.forEach(f => {
      this.checkgeneralCategoryAry.push(f)
    })
    // this.setofvalues.forEach(s => {
    //   s.isChecked = false;
    //   if (this.generalCategoryAry != undefined) {
    //     this.generalCategoryAry.forEach(g => {
    //       if (s.valueCode == g) {
    //         s.isChecked = true;
    //       }
    //     })
    //   }
    // })
    this.initData();
  }

  /**
    * 创建表单
    * 
    * 
    * @memberof TurbineEditComponent
    */
  createForm() {
    let obj: {} = {
      'operCategoryName': [this.currentEntity.operCategoryName, [
        Validators.required,
        Validators.pattern('^[\u4e00-\u9fa5_a-zA-Z0-9]{1,20}'),
        Validators.maxLength(20)
      ], (control: FormControl): any => this.operCategoryNameAsnyValidator(control)],
      //(control: FormControl): any => this.operCategoryNameAsnyValidator(control)
      'operCategoryCode': [this.currentEntity.operCategoryCode, [
        Validators.required,
        Validators.maxLength(20)
      ], (control: FormControl): any => this.operCategoryCodeAsnyValidator(control)],
      // (control: FormControl): any => this.operCategoryCodeAsnyValidator(control)
      'operCategoryIcon': [this.currentEntity.operCategoryIcon, [
        Validators.maxLength(20)
      ],],
      'enabled': [this.currentEntity.enabled, []],
      'autoFinish': [this.currentEntity.autoFinish, []],
      'controlTurb': [this.currentEntity.controlTurb, []],
      'isStatistic': [this.currentEntity.isStatistic, []],
      'operCategorySeq': [this.currentEntity.operCategorySeq, [
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ],],
      'operCategoryColor': [this.currentEntity.operCategoryColor, [
        Validators.maxLength(20)
      ],],
      'operCategoryKey': [this.currentEntity.operCategoryKey, [
        Validators.required,
        Validators.pattern('[a-zA-Z]{1,255}'),
        Validators.maxLength(255)
      ], (control: FormControl): any => this.operCategoryKeyAsnyValidator(control)],
      // 'notAllowWhenStatus': [this.currentEntity.notAllowWhenStatus, [],],
      // 'generalCategory': [this.currentEntity.generalCategory, [],],
    }
    this.formGroup = this.fromBuider.group(obj);
  }

  /**
 * 设置表单错误对象
 * 
 * 
 * @memberof BladeContainerBase
 */
  setFormError(): void {
    this.formErrors = {
      'operCategoryName': '',
      'operCategoryCode': '',
      'operCategoryIcon': '',
      'enabled': '',
      'autoFinish': '',
      'controlTurb': '',
      'isStatistic': '',
      'operCategorySeq': '',
      'operCategoryColor': '',
      'operCategoryKey': ''
      // 'notAllowWhenStatus': '',
      // 'generalCategory': ''
    };
  }
  /**
  * 设置表单验证信息
  * 
  * 
  * @memberof BladeContainerBase
  */
  setValidationMessages(): void {
    this.validationMessages = {
      'operCategoryName': {
        'exist': '已存在。',
        'required': '不能为空。',
        'pattern': '格式不正确',
        'maxlength': '不能多于20个字符长度。',
      },
      'operCategoryCode': {
        'exist': '已存在。',
        'required': '不能为空。',
        'maxlength': '不能多于20个字符长度。',
      },
      'operCategoryIcon': {
        'maxlength': '不能多于20个字符长度。',
      },
      'enabled': {
      },

      'operCategorySeq': {
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
      },
      'operCategoryColor': {
        'maxlength': '不能多于20个字符长度。',
      },
      'operCategoryKey': {
        'required': '不能为空。',
        'pattern': '由字母组成。',
        'maxlength': '不能多于255个字符长度。',
        'exist': '已存在。',

      }
      // 'notAllowWhenStatus': {},
      // 'generalCategory': {},
    };
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;
    this.currentEntity.operCategoryName = formValue.operCategoryName;
    this.currentEntity.operCategoryCode = formValue.operCategoryCode;
    this.currentEntity.operCategoryIcon = formValue.operCategoryIcon;
    this.currentEntity.enabled = formValue.enabled;
    this.currentEntity.autoFinish = formValue.autoFinish;
    this.currentEntity.controlTurb = formValue.controlTurb;
    this.currentEntity.isStatistic = formValue.isStatistic;
    this.currentEntity.operCategorySeq = formValue.operCategorySeq;
    this.currentEntity.operCategoryColor = formValue.operCategoryColor;
    this.currentEntity.operCategoryKey = formValue.operCategoryKey;
    this.currentEntity.notAllowWhenStatus = this.checkStatusAry.join('|');
    this.currentEntity.generalCategory = this.checkgeneralCategoryAry.join('|');
  }
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();

      this.turboperCategoryService.create(this.currentEntity)
        .then(res => {
          if (res == 200) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.parentBlade.bladeData.isLoading = false;
            this.bladeService.closeBlade(this.currentBlade);
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent();
      return this.turboperCategoryService.update(this.currentEntity)
        .then(res => {
          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.parentBlade.bladeData.isLoading = false;
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  setofvalueIsChecked(check: boolean, setofvalue: Setofvalue) {
    let index = this.checkgeneralCategoryAry.findIndex(o => o == setofvalue.valueCode)
    if (check) {
      if (index < 0) {
        this.checkgeneralCategoryAry.push(setofvalue.valueCode);
        setofvalue.isChecked = true;
      }
    } else {
      if (index > -1) {
        this.checkgeneralCategoryAry.splice(index, 1);
        setofvalue.isChecked = false;
      }
    }
    this.hasturbStatuChange();
  }

  turbStatuIsChecked(check: boolean, turbStatu: TurbStatus) {
    let index = this.checkStatusAry.findIndex(o => Number(o) == turbStatu.statusValue)
    if (check) {
      if (index < 0) {
        this.checkStatusAry.push(turbStatu.statusValue.toString());
        turbStatu.isChecked = true;
      }
    } else {
      if (index > -1) {
        this.checkStatusAry.splice(index, 1);
        turbStatu.isChecked = false;
      }
    }
    this.hasChange();
  }

  hasturbStatuChange(): boolean {
    if (this.notStatusAry != null) {
      if (this.checkStatusAry) {
        if (this.checkStatusAry.length != this.notStatusAry.length) {
          return true
        } else {
          let change: boolean = false;
          this.checkStatusAry.forEach(s => {
            if (!this.notStatusAry.find(o => o == s)) {
              change = true;
              return;
            }
          })
          return change;
        }
      } else {
        return true;
      }
    } else {
      if (!this.checkStatusAry) {
        return false;
      }
      return true
    }
  }
  hasChange(): boolean {
    if (this.formGroup != null) {
      let enity = this.formGroup.value;
      let names: string[] = Object.getOwnPropertyNames(enity);
      for (let i: number = 0; i < names.length; i++) {
        let name = names[i];
        if (this.currentEntity.hasOwnProperty(name)) {
          let value = Object.getOwnPropertyDescriptor(this.currentEntity, name).value;
          if (value != enity[name]) {
            return true;
          }
        }
      }
    }


    if (this.generalCategoryAry != null) {
      if (this.checkgeneralCategoryAry) {
        if (this.checkgeneralCategoryAry.length != this.generalCategoryAry.length) {
          return true
        } else {
          let change: boolean = false;
          this.checkgeneralCategoryAry.forEach(s => {
            if (!this.generalCategoryAry.find(o => o == s)) {
              change = true;
              return;
            }
          })
          return change;
        }
      } else {
        return true;
      }
    } else {
      if (!this.checkgeneralCategoryAry) {
        return false;
      }
      return true;
    }


  }

  //异步校验名字
  operCategoryNameAsnyValidator(control: FormControl): any {
    if (!control.value || control.value == this.currentEntity.operCategoryName) {
      return Observable.of(null);
    }
    return this.turboperCategoryService.hasOperCategoryName(control.value, this.currentEntity.operCategoryId)
      .map(res => res ? { exist: true } : null);
  }

  //异步校验code
  operCategoryCodeAsnyValidator(control: FormControl): any {
    if (!control.value || control.value == this.currentEntity.operCategoryCode) {
      return Observable.of(null);
    }
    return this.turboperCategoryService.hasOperCategoryCode(control.value, this.currentEntity.operCategoryId)
      .map(res => res ? { exist: true } : null);
  }
  operCategoryKeyAsnyValidator(control: FormControl): any {
    if (!control.value || control.value == this.currentEntity.operCategoryKey) {
      return Observable.of(null);
    }
    return this.turboperCategoryService.hasOperCategoryKey(control.value, this.currentEntity.operCategoryId)
      .map(res => res ? { exist: true } : null);
  }

}



// WEBPACK FOOTER //
// ./src/app/module/basic/turboper-category/turboper-category-edit/turboper-category-edit.component.ts